<template>
  <div v-show="mappingProps.visible" class="tr-tagFilter" tabindex="-1">
    <div class="scroll-box">
      <div class="box" :style="boxDivStyle">
        <div class="list" ref="listDiv">
          <t-chip
            class="tr-chip-tagFilter tr-chip-select-type-moon item"
            :class="{ 'z-mobile': isMobile }"
            :ref="e => (chipRefList[index] = e)"
            @focus="handleClickChip(index)"
            @click="handleClickChip(index)"
            v-for="({ code, name, tip }, index) in list"
            :selected="tagIsActive(code)"
            @update:selected="shiftSelectTag(code)"
            size="20px"
            :tabindex="mappingProps.tabIndex"
          >
            <span
              >{{ name
              }}<Tooltip
                v-if="!isMobile && !mappingProps.visibleHelpPopover && tip"
                class="t-help-popover"
                helpPlacement="bottom"
                :offset="[8, 8]"
              >
                {{ tip }}
              </Tooltip>
            </span>

            <HelpPopover
              v-if="!isMobile && mappingProps.visibleHelpPopover && tip"
              style="margin-left: 2px"
              :helpTooltip="tip"
              :helpConf="!!tip"
              helpPlacement="bottom"
            />
          </t-chip>

          <div class="none-hint" v-if="inDesign && list.length === 0"
            >当前无标签条件，请配置筛选字段</div
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup type="typescript">
import { computed, useAttrs, ref, nextTick, watch, onMounted } from 'vue';
// 公共方法
import useMappingProps from 't/common/hooks/useMappingProps';
import useEnv from 't/common/hooks/useEnv';
import { commonProps } from 't/common/utils';
// 组件
import TChip from 't/basic/chip/Component.vue'
import HelpPopover from 't/basic/help-popover';
import Tooltip from '@teld/q-components/Tooltip';
// 用例层
import Presenter from "./modules/presenter";
// 接口层
import Interface from "./modules/interface";

// 直接映射透传qursor的属性
const attrs = useAttrs();
// 组件传参
const props = defineProps(
	{
		...commonProps,

		pageCode: String,
		instanceCode: String,

		// 是否可见
		visible: {
			type: Boolean,
			default: true
		},

		filterFields: { type: Array, default: () => [] },

		tabIndex: {
			type: [String, Number],
			default: '1'
		},

		visibleHelpPopover: {
			type: Boolean,
			default: false
		},

		enableUserConfig: {
			type: Boolean,
			default: false
		},
	},
);
// 大写首字母属性
const [mappingProps, mappingExpose] = useMappingProps(props);

// 是否设计时
const { inDesign, isMobile } = useEnv();

// 触发的emit事件
const emit = defineEmits(['change']);

// 为了不显示多余的空白
const listDiv = ref(null)
const boxDivStyle = ref('');
function getBoxDivStyle() {
	const { offsetWidth } = listDiv.value;
	console.log('=========== offsetWidth', offsetWidth, listDiv.value)
	return {
		width: offsetWidth + 2 + 'px'
	}
}
function resetBoxDivStyle() {
	boxDivStyle.value = { width: '10000%' }
	setTimeout(() => {
		boxDivStyle.value = getBoxDivStyle()
	}, 50)
}

// 为了显示剩余的chip
const chipRefList = [];
function handleClickChip(index) {
	if (chipRefList[index - 1]) chipRefList[index - 1].$el.scrollIntoViewIfNeeded()
	if (chipRefList[index + 1]) chipRefList[index + 1].$el.scrollIntoViewIfNeeded()
	if (chipRefList[index]) chipRefList[index].$el.scrollIntoViewIfNeeded()
}

// 用例实例
const presenter = new Presenter(JSON.parse(JSON.stringify(mappingProps.filterFields)));
const list = ref(presenter.list);
const selectedCodeList = ref(presenter.getSelectedCodeList());
const tagIsActive = computed(() => {
	return function (code) {
		return selectedCodeList.value.findIndex(v => v === code) != -1
	}
})

function shiftSelectTag(code) {
	presenter.shiftSelectTag(code);
	selectedCodeList.value = presenter.getSelectedCodeList();
	// 通知外部
	emitChangeFn()

	if (!inDesign && mappingProps.enableUserConfig) {
		// 存储配置
		saveSelected();
	}
}

function emitChangeFn() {
	emit('change', {
		selectedCodeList: selectedCodeList.value,
		list: list.value,
		filterFields: mappingProps.filterFields
	});
}

function initPresenter(filterFields) {
	presenter.init(filterFields);
	list.value = presenter.list;
	selectedCodeList.value = presenter.getSelectedCodeList();
	// 通知外部
	emitChangeFn()
}
// 设计时可能会改动配置项
watch(() => mappingProps.filterFields, (val, oldVal) => {
	if (!oldVal || JSON.stringify(val) !== JSON.stringify(oldVal)) {
		initPresenter(val);

		resetBoxDivStyle();
	}
})

// 存储用户配置
const ProfileKey = { Key: `tag-filter-${mappingProps.instanceCode}-${mappingProps.pageCode}`, DynamicKey: '' };

async function iniSelected() {
	const { status, data } = await Interface.getUserProfile(ProfileKey);
	if (status === 'success') {
		presenter.setSelectedCodeList(data);
		selectedCodeList.value = presenter.getSelectedCodeList();
	}
	// 通知外部，需要主动触发数据表格的更新
	emitChangeFn();
}

async function saveSelected() {
	const { status, data } = await Interface.saveUserProfile(ProfileKey, selectedCodeList.value);
	if (status !== 'success' && typeof data === 'string' && data) {
		this.notify({
			caption: Terms.Notify.warningTitle,
			type: 'warning',
			message: data,
		});
	}
}

onMounted(() => {
	if (!inDesign && mappingProps.enableUserConfig) {
		iniSelected()
	}

	setTimeout(() => {
		resetBoxDivStyle()
	}, 100)

	window.addEventListener('resize', () => resetBoxDivStyle())
})

// 暴漏外部
defineExpose({
	...mappingExpose,

	getFilterExpression(AdvanceFilter) {
		return presenter.getFilterExpression(AdvanceFilter)
	},

	getFilterExpressionString(AdvanceFilter) {
		return presenter.getFilterExpressionString(AdvanceFilter)
	},
});
</script>

<style lang="scss">
@import './index.scss';
</style>
